package cn.fsw.pethome.user.service.impl;

import cn.fsw.pethome.base.service.impl.BaseServiceImpl;
import cn.fsw.pethome.constants.BaseConstants;
import cn.fsw.pethome.user.domain.Logininfo;
import cn.fsw.pethome.user.domain.User;
import cn.fsw.pethome.user.domain.dto.UserDTO;
import cn.fsw.pethome.user.domain.dto.UserEmailDTO;
import cn.fsw.pethome.user.mapper.LogininfoMapper;
import cn.fsw.pethome.user.mapper.UserMapper;
import cn.fsw.pethome.user.service.IUserService;
import cn.fsw.pethome.util.BusinessException;
import cn.fsw.pethome.util.MD5Utils;
import cn.fsw.pethome.util.StrUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fsw
 * @since 2022-10-13
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    @Transactional
    public void register(UserDTO userdto) {
        //注册功能的实现
        //1.验证手机号是否为null
        if(StringUtils.isEmpty(userdto.getPhone())){
            throw new BusinessException("手机号不能为空");
        }
        //2.手机验证码是否为null
        if(StringUtils.isEmpty(userdto.getCode())){
            throw new BusinessException("手机验证码不能为空");
        }
        //3.密码是否为null
        if(StringUtils.isEmpty(userdto.getPassword())){
            throw new BusinessException("密码不能为空");
        }
        //4.确认密码是否为null
        if(StringUtils.isEmpty(userdto.getPasswordRepeat())){
            throw new BusinessException("确认密码不能为空");
        }
        //5.密码和确认密码是否一致
        if(!userdto.getPassword().equals(userdto.getPassword())){
            throw new BusinessException("两次输入的密码不一致");
        }
        //6.手机号是否被注册过
        User user = userMapper.selectByPhoneUser(userdto.getPhone());
        if(user != null){
            throw new BusinessException("该手机号已被注册");

        }
        //7.根据手机号+业务键 去redis中获取手机验证
        Object code = redisTemplate.opsForValue().get(BaseConstants.register.REGISTER + userdto.getPhone());
        //7.1 有
        if(code != null){
        //7.1.1 判断两个验证码是否一致
            String[] split = code.toString().split(":");
            if (split[0].equalsIgnoreCase(userdto.getCode())) {
        //7.1.2 将数据保存到数据库
                User user1 = new User();
                user1.setPhone(userdto.getPhone());
                user1.setPassword(userdto.getPassword());
                user1.setUsername(userdto.getPhone());
                user1.setState(BaseConstants.User.STATE_ACTIVATED);
                this.add(user1);
            }else {
                throw new BusinessException("验证码输入错误");
            }
        }else {
        //7.2 无
        //7.2.1 直接抛出 验证已失效
            throw new BusinessException("验证码已过期,请重新获取");

        }

    }

    @Override
    @Transactional
    public void EmailRegistration(UserEmailDTO userEmailDTO) {
        //验证邮箱是否为空
        if (StringUtils.isEmpty(userEmailDTO.getEmail())){
            throw new BusinessException("邮箱不能为空");
        }
        //密码是否为null
        if(StringUtils.isEmpty(userEmailDTO.getPassword())){
            throw new BusinessException("密码不能为空");
        }
        //确认密码是否为null
        if(StringUtils.isEmpty(userEmailDTO.getPasswordRepeat())){
            throw new BusinessException("确认密码不能为空");
        }
        //密码和确认密码是否一致
        if(!userEmailDTO.getPassword().equals(userEmailDTO.getPassword())){
            throw new BusinessException("两次输入的密码不一致");
        }
        //邮箱是否被注册过
        User user = userMapper.selectByEmailUser(userEmailDTO.getEmail());
        if(user != null){
            throw new BusinessException("该手机号已被注册");

        }
        //将数据保存到数据库
        User user1 = new User();
        user1.setEmail(userEmailDTO.getEmail());
        user1.setUsername(userEmailDTO.getEmail());
        user1.setPassword(userEmailDTO.getPassword());
        user1.setState(BaseConstants.User.STATE_REGISTERED);
        this.add(user1);

        //发送激活信息到邮箱
        String msg = "<h1>恭喜您已成功注册,点击链接激活</h1>"+"<a href='http://localhost:8080/user/activation/"+user1.getId()+"'>激活</a>";
        sendEmail(msg,user1.getEmail());
    }
    //激活
    @Override
    @Transactional
    public void activation(Long id) {
        User user = userMapper.selectById(id);
        user.setState(BaseConstants.User.STATE_ACTIVATED);
        userMapper.update(user);
    }

    @Override
    @Transactional
    public void add(User user) {
        this.encrypt(user);
        //7.1.3 将logininfo也保存一份
        Logininfo logininfo = new Logininfo();
        /*将user的数据复制一份到logininfo*/
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setDisable(1);//可用
        logininfo.setType(1);//用户
        logininfoMapper.add(logininfo);
        user.setLogininfo_id(logininfo.getId());
        userMapper.add(user);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        User user = userMapper.selectById(id);
        logininfoMapper.delete(user.getLogininfo_id());
        userMapper.delete(id);
    }
    /*完成user和logininfo的同步*/
    @Override
    @Transactional
    public void update(User user) {
        super.update(user);
        User user1 = userMapper.selectById(user.getId());
        Long logininfoId = user1.getLogininfo_id();
        Logininfo logininfo = logininfoMapper.selectById(logininfoId);
        Long id = logininfo.getId();//获取之前的id
        BeanUtils.copyProperties(user1,logininfo);//将修改后的user赋值给logininfo
        logininfo.setId(id);//将之前的id设置回来
        logininfoMapper.update(logininfo);
    }

    /*给密码加密*/
    private void encrypt(User user){
        /*随机生成32位*/
        String complexRandomString = StrUtils.getComplexRandomString(32);
        user.setSalt(complexRandomString);//盐值
        String pwd = MD5Utils.encrypByMd5(user.getPassword() + complexRandomString);
        user.setPassword(pwd);

    }

    /*发送邮箱的方法
     * */
    private void sendEmail(String msg,String email){
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1754214044@qq.com");
            helper.setSubject("邮箱注册审核结果通知");
            //第二个参数 true 代表是否是一个html内容
            helper.setText(msg, true);
        /*//添加附件
        helper.addAttachment("文件名.jpg",new File("C:\\aa.jpg"));
        helper.addAttachment("压缩文件", new File("C:\\resources.zip"));*/
            //收件人
            helper.setTo(email);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
